import util from "../../util";
import tools from "public/tools/index";

export default class parentInstanceCollection {
  constructor(clz, api) {
    this.util = util;
    this.info = [];
    this.infoTree = [];
    this.infoCascader = [];
    this.list = [];
    this.listTree = [];
    this.listCascader = [];
    this.records = [];
    this.recordsTree = [];
    this.recordsCascader = [];
    this.api = api;
    this.clz = clz;
    this.valueRecords = [];
  }
  setRecords(records) {
    this.records = records;
  }
  /***
   * 批量新增
   * @param records
   * @returns {Promise<boolean|*>}
   */
  async batchAdd(records) {
    let result = await this.api
      .batchAdd(records)
      .then((data) => {
        if (!!data) {
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /***
   * 批量更新
   * @param records
   * @returns {Promise<boolean|*>}
   */
  async updateByIds(records) {
    let result = await this.api
      .updateByIds(records)
      .then((data) => {
        if (!!data) {
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 批量删除
   * */
  async deleteByCondition(condition, otherParams = {},like=false) {
    let filterStr = condition;
    if (condition.constructor === Object) {
      filterStr = this.setFilteStr(condition, like);
    }
    
    let result = await this.api
      .deleteByCondition({ condition: filterStr,... otherParams})
      .then((flag) => {
        if (flag) {
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async deleteByIds(ids) {
    let result = await this.api
      .deleteByIds(ids)
      .then((flag) => {
        if (flag) {
          this.deleteRecords(ids);
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async queryByIds(ids) {
    let result = await this.api
      .queryByIds(ids)
      .then((data) => {
        if (!!data) {
          this.records = data;
          this.setValueRecords();
          // this.total = this.records.length || 0;
          this.recordsTree = util.getTree(data, "type", "className");
          this.recordsCascader = util.getCascader(
            data,
            "type",
            "className"
          );
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async deleteByClassNames(classNames) {
    let result = await this.api
      .deleteByClassNames(classNames)
      .then((flag) => {
        if (flag) {
          this.deleteRecords(classNames, "className");
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async deleteByInstanceIds(instanceIds) {
    let result = await this.api
      .deleteByInstanceIds(instanceIds)
      .then((flag) => {
        if (flag) {
          this.deleteRecords(instanceIds, "instanceId");
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 条件查询，当前版本，不分页
   * */
  async query(
    condition,
    hierValueCondition = "",
    otherParams = {},
    like = false
  ) {
    hierValueCondition = hierValueCondition || "1=1";
    let filterStr = condition;
    if (condition.constructor === Object) {
      filterStr = this.setFilteStr(condition, like);
    }
    let hierFilterStr = hierValueCondition;
    if (hierValueCondition.constructor === Object) {
      hierFilterStr = this.setFilteStr(hierValueCondition, like);
    }
    let result = await this.api
      .query({
        condition: filterStr,
        hierValueCondition: hierFilterStr,
        ...otherParams,
      })
      .then((data) => {
        if (!!data) {
          this.records = data;
          this.setValueRecords();
          this.recordsTree = util.getTree(data, "type", "className");
          this.recordsCascader = util.getCascader(data, "type", "className");
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 条件查询，当前版本，分页
   * */
  async queryByPage(
    pageNumber,
    pageSize,
    condition,
    hierValueCondition = "",
    orderBy = "",
    hiddenHierData = true,
    like = false
  ) {
    let filterStr = condition;
    if (condition.constructor === Object) {
      filterStr = this.setFilteStr(condition, like);
    }
    let hierFilterStr = hierValueCondition;
    if (hierValueCondition.constructor === Object) {
      hierFilterStr = this.setFilteStr(hierValueCondition, like);
    }
    let result = await this.api
      .queryByPage(pageNumber, pageSize, {
        condition: filterStr,
        hierValueCondition: hierFilterStr,
        orderBy,
        hiddenHierData,
      })
      .then((data) => {
        if (!!data) {
          this.records = data.records;
          this.total = data.recordCount;
          this.setValueRecords();
          // this.total = this.records.length || 0;
          this.recordsTree = util.getTree(data.records, "type", "className");
          this.recordsCascader = util.getCascader(
            data.records,
            "type",
            "className"
          );
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /********************************************************************************************
   * 摘要查询
   * ******************************************************************************************/
  /**
   * 摘要查询，当前版本，不分页
   * */
  async listAllInfo() {
    let result = await this.api
      .queryInfo({})
      .then((data) => {
        if (!!data) {
          this.info = data;
          this.infoTree = util.getTree(data, "type", "className");
          this.infoCascader = util.getCascader(data, "type", "className");
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 摘要查询，当前版本，分页
   * */
  async queryInfoByPage(pageNumber, pageSize, filter) {
    let result = await this.api
      .queryInfoByPage(pageNumber, pageSize, { condition: filter })
      .then((data) => {
        if (!!data) {
          this.records = data.records;
          this.total = data.recordCount;
          // this.total = this.records.length || 0;
          this.setValueRecords();
          this.recordsTree = util.getTree(data.records, "type", "className");
          this.recordsCascader = util.getCascader(
            data.records,
            "type",
            "className"
          );
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }

  /********************************************************************************************
   * 版本管理
   * ******************************************************************************************/
  /**
   * 摘要查询，所有版本，不分页
   * */
  async listAllVersionInfo() {
    let result = await this.api
      .queryInfoIncludeUnpublished({})
      .then((data) => {
        if (!!data) {
          this.info = data;
          this.infoTree = util.getTree(data, "type", "className");
          this.infoCascader = util.getCascader(data, "type", "className");
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 全部查询，所有版本，分页
   * */
  async listAllVersion() {
    let result = await this.api
      .queryIncludeUnpublished({})
      .then((data) => {
        if (!!data) {
          this.list = data;
          this.listTree = util.getTree(data, "type", "className");
          this.listCascader = util.getCascader(data, "type", "className");
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  // 公共方法，用来操作this.records
  addRecord(record) {
    this.records.unshift(record);
    this.setValueRecords();
  }
  updateRecord(record, key = "id") {
    let index = this.records.findIndex((item) => item[key] === record[key]);
    if (index !== -1) {
      this.records.splice(index, 1, record);
      this.setValueRecords();
    }
  }
  deleteRecords(list, key = "id") {
    list.forEach((value) => {
      let index = this.records.findIndex((item) => item[key] === value);
      if (index !== -1) {
        this.records.splice(index, 1);
        this.setValueRecords();
      }
    });
  }
  calcFilter(filter, searchCondition) {
    let newFilter = "";
    if (tools.isReal(filter)) {
      newFilter = util.getFilter(filter);
    }
    newFilter =
      searchCondition +
      (searchCondition && newFilter ? " and " : "") +
      newFilter;
    return newFilter;
  }
  setFilteStr(filter, like = true) {
    if (!!filter && filter.constructor === Object) {
      for (let key in filter) {
        (filter[key] === "" || filter[key] === null) && delete filter[key];
      }
    } //删除查询项中属性值为空的查询条件
    filter = this.bulidFilter(filter, like ? "like" : "=");
    return filter;
  }
  bulidFilter(filterMap, sign = "like") {
    let arr = [];
    if (!!filterMap) {
      Object.keys(filterMap).map((key) => {
        let curItem = filterMap[key];
        let type = typeof curItem;
        let strWrap = type === "number" || type === "boolean" ? "" : "'";

        if (curItem !== "" && curItem !== undefined && curItem !== null) {
          if (
            sign === "like" &&
            strWrap &&
            key != "className" &&
            key != "type" &&
            key != "id"
          ) {
            arr.push(`${key} like ${strWrap}%${curItem}%${strWrap}`);
          } else {
            arr.push(`${key} ${"=="} ${strWrap}${curItem}${strWrap}`);
          }
        }
      });
    }
    return arr.join(" && ");
  }
  setValueRecords() {
    this.valueRecords = this.records.map((d) => {
      if (d.values) {
        return {
          ...d.values,
          ...d,
        };
      }
    });
    return this.valueRecords;
  }
}
